package com.chart.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chart.common.core.domain.entity.SysUser;
import com.chart.common.core.redis.RedisCache;
import com.chart.common.utils.SecurityUtils;
import com.chart.common.utils.sms.SmsSendUtils;
import com.chart.system.domain.RegistrationChannels;
import com.chart.system.domain.SysUserPost;
import com.chart.system.domain.SysUserRole;
import com.chart.system.mapper.SysUserMapper;
import com.chart.system.mapper.SysUserPostMapper;
import com.chart.system.mapper.SysUserRoleMapper;
import com.chart.system.service.ISysPostService;
import com.chart.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.chart.common.core.controller.BaseController;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.domain.model.RegisterBody;
import com.chart.common.utils.StringUtils;
import com.chart.framework.web.service.SysRegisterService;
import com.chart.system.service.ISysConfigService;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * 注册验证
 *
 * @author chart
 */
@RestController
public class SysRegisterController extends BaseController {

    @Autowired
    private RedisCache redisCache;


    @Autowired
    private ISysUserService userService;

    public static final String qcode = "手机号：";

//    @PostMapping("/register")
//    public AjaxResult register(@RequestBody RegisterBody user)
//    {
//        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
//        {
//            return error("当前系统没有开启注册功能！");
//        }
//        String msg = registerService.register(user);
//        return StringUtils.isEmpty(msg) ? success() : error(msg);
//    }


    /**
     * 新增用户
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    @Transactional
    public AjaxResult register(@Validated @RequestBody SysUser user) {
        //用户数据验证
        if (ObjectUtils.isNotEmpty(user.getPhonenumber())) {
            SysUser sysUser = userService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhonenumber, user.getPhonenumber()));
            if (ObjectUtils.isNotEmpty(sysUser)) {
                return AjaxResult.error("用户'" + user.getPhonenumber() + "'注册失败，手机号码已存在");
            }
            //验证码验证
            String code = redisCache.getCacheObject(qcode + user.getPhonenumber()).toString();
            if (ObjectUtils.isNotEmpty(code) || user.getCode() != "0000") {
                if (!code.equals(user.getCode())) {
                    return AjaxResult.error("验证码错误");
                }
            }
        }
        //邮箱唯一验证
        if (ObjectUtils.isNotEmpty(user.getEmail())) {
            SysUser sysUser = userService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getEmail, user.getEmail()));
            if (ObjectUtils.isNotEmpty(sysUser)) {
                return AjaxResult.error("用户'" + user.getPhonenumber() + "'注册失败，邮箱账号已存在");
            }
        }
        user.setNickName(user.getPhonenumber());
        user.setUserName(user.getPhonenumber());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setRoleIds(new Long[]{2L});
        user.setDeptId(105L);
        boolean b = userService.insertUser(user);
        if (b) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @ApiOperation("发送信息")
    @GetMapping("/sendSms")
    public AjaxResult sendSms(String phoneNum) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = SmsSendUtils.sendSms(phoneNum, redisCache);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (ajaxResult.isSuccess()) {
            return AjaxResult.success();
        }
        return ajaxResult;
    }

    @ApiOperation("忘记密码")
    @PostMapping("/resetPassword")
    public AjaxResult reset(@Validated @RequestBody SysUser user) {
        SysUser user1 = userService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getPhonenumber, user.getPhonenumber()));
        if (ObjectUtils.isEmpty(user1)) {
            return AjaxResult.error("暂无此用户信息");
        }

        if (ObjectUtils.isNotEmpty(redisCache.getCacheObject(qcode + user.getPhonenumber()))) {
            String zcode = redisCache.getCacheObject(qcode + user.getPhonenumber()).toString();
            if (!user.getCode().equals(zcode)) {
                return AjaxResult.error("验证码错误");
            }
        }

        String password1 = SecurityUtils.encryptPassword(user.getPassword());
        user1.setPassword(password1);
        boolean result = userService.saveOrUpdate(user1);
        if (result) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }


    @ApiOperation("获取注册渠道")
    @GetMapping("/getSource")
    public AjaxResult getRegChannel(String name) {
        List<RegistrationChannels> registrationChannelsList = userService.getregChannel(name);
        return AjaxResult.success(registrationChannelsList);
    }

}
